// pages/order/order-add/index.js
const util = require("../../../../utils/util.js");
const regeneratorRuntime = require("../../../../utils/runtime");
const db = wx.cloud.database()
const app = getApp();
Page({
  data: {
    is_onshow: false,
    color: app.ext.color,
    address: null,
    cartData: [],
    buyData:[],
    totalPrice: 0,
    payment: [ {
        name: '微信支付',
        payment_id: 0
    },{
        name: '货到付款',
        payment_id: 1
      }], // 0微信，1货到付款
    pay_index: 0,
    coupon_id: 0, // 使用的优惠券id
    deliveryPrice: 0, // 满减价格
    couponPrice: 0, // 优惠券价格
    xiaojiPrice: 0, // 小计
    hejiPrice: 0, // 合计
    feePrice: 0, // 订单运费
    free_delivery: 0, // 是否包邮
    showModal: false,
    no_use_coupon: 0, // 不适用优惠券
    modalHeight: util.rpxToPx(-670) ,// 购物车弹窗高度,
    state:0,
    out_trade_no:'',
    order: {}
  },
  onLoad(options) {
    if (options.form_cart) {
      this.data.form_cart = Number(options.form_cart);
    }
    // 获取默认收货地址
    if (wx.getStorageSync("shippingAddress")) {
      this.setData({
        address: wx.getStorageSync("shippingAddress")
      });
    }

    if (this.data.form_cart) {
      this.data.cartData = JSON.parse(wx.getStorageSync('cart-data'));
    } else {
      this.data.cartData = JSON.parse(wx.getStorageSync('save-now'));
    }
    console.log(this.data.cartData)


    let tmpData = this.data.cartData;
    for (var k = 0; k < tmpData.length; k++) {
      console.log(k);
      console.log(tmpData[k].skuData.length)
    if(tmpData[k].skuData.length==0){
      //说明是规格产品
    }else{
    //     let name = tmpData[k].name;
    //     for (var i = 0; i < tmpData[k].skuData.length; i++) {
    //       for (var j = 0; j < tmpData[k].skuData[i].ggsx.length; j++) {
    //         if (tmpData[k].skuData[i].ggsx[j].is_select == '1') {
    //           name = name + " " + tmpData[k].skuData[i].ggsx[j].name;
    //         }
    //       }
    //     }
    //     tmpData[k].name = name;
        
     
    }
    }
      this.setData({
        buyData : tmpData
      })
  },
  onShow() {
    if (!this.data.is_onshow) {
      this.setData({
        is_onshow: true
      })
      this.getTotalprice();
    }
  },
  getTotalprice() {
    if (this.data.cartData.length>0) {
      let totalPrice = 0;
      let totalNum = 0;
      this.data.cartData.forEach(val => {
        totalPrice += (val.skuData.length>0 ? val.skuPrice : val.price) * val.num;
        totalNum += val.num;
      })
      this.data.xiaojiPrice = this.data.hejiPrice = totalPrice;
      // 运费
      let unite_fee = 0; // 全国统一运费
      this.data.cartData.forEach(val => {
        if (val.yf>0) {
          unite_fee += val.yf;
        }
      })
      // TODO 计算满减
      db.collection('user_coupon').where({ state: 0, openid: wx.getStorageSync('openid'),diyId:wx.getStorageSync('diyId') }).orderBy("createtime", 'desc').get().then(res => {
        const DATA = res.data;
        let tmpCou = [];
        for(var i=0;i<DATA.length;i++){
          if (DATA[i].endtime > new Date().getTime()) {  //说明没有过期了
            tmpCou.push(DATA[i])
          }
        }
        
        this.setData({
          coupon:tmpCou
        })
        console.log(totalNum);
        console.log(totalPrice);
        console.log(unite_fee);
        this.setData({
          totalPrice: totalPrice,
          totalNum: totalNum,
          feePrice: unite_fee,
          xiaojiPrice: this.data.xiaojiPrice,
          hejiPrice: this.data.xiaojiPrice + unite_fee
        })

      })
      
    }
  },
  hideModal() {
    let animation = wx.createAnimation({
      duration: 200,
      timingFunction: 'linear'
    })
    animation.translateY(0).step();
    this.setData({
      animationData: animation.export()
    })
    setTimeout(() => {
      animation.translateY(this.data.modalHeight).step();
      this.setData({
        animationData: animation.export(),
        showModal: false
      })
    }, 200)
  },
  showModal(e) {
    let animation = wx.createAnimation({
      duration: 200, // 动画持续时间
      timingFunction: 'linear' // 定义动画效果，当前是匀速
    })
    animation.translateY(0).step();
    this.setData({
      animationData: animation.export(), // 通过export()方法导出数据
      showModal: true
    })
    // 设置setTimeout来改变y轴偏移量，实现有感觉的滑动
    setTimeout(() => {
      animation.translateY(this.data.modalHeight).step();
      this.setData({
        animationData: animation.export()
      })
    }, 200)
  },
  couponSelect(e) {
    const item = e.currentTarget.dataset.item;
    let coupon = this.data.coupon;
    for (let val of coupon) {
      if (val._id == item._id) {
        val.is_select = 1;
        this.data.couponPrice = val.price;
        this.data.coupon_id = val._id;
      } else {
        val.is_select = 0;
      }
    }
    this.setData({
      no_use_coupon: 0,
      coupon: coupon,
      couponPrice: this.data.couponPrice,
      totalPrice: this.data.totalPrice - this.data.couponPrice,
      hejiPrice: this.data.hejiPrice - this.data.couponPrice,
      xiaojiPrice: this.data.xiaojiPrice - this.data.couponPrice
    })
    console.log(this.data.totalPrice)
    console.log(this.data.couponPrice)
    this.hideModal();
  },
  noUseCoupon() {
    let coupon = this.data.coupon;
    if (coupon) {
      for (let val of coupon) {
        val.is_select = 0;
      }
    }
    this.setData({
      totalPrice: this.data.totalPrice + this.data.couponPrice,
      hejiPrice: this.data.hejiPrice + this.data.couponPrice,
      xiaojiPrice: this.data.xiaojiPrice + this.data.couponPrice
    })
    this.setData({
      coupon: coupon ? coupon : [],
      no_use_coupon: 1,
      couponPrice: 0,
      coupon_id: 0
    })
    
    this.hideModal();
  },
  // 选择收货地址
  goAddress: function (e) {
    wx.removeStorageSync("shippingAddress");
    let that = this;
    wx.chooseAddress({
      success: function (res) {
        let _address = {
          userName: res.userName,
          telNumber: res.telNumber,
          nationalCode: res.nationalCode,
          addr: res.provinceName + res.cityName + res.countyName + res.detailInfo
        };
        wx.setStorageSync("shippingAddress", _address);
        // 计算运费
        that.setData({
          address: _address
        });
      }
    });
  },
  // 选择支付方式
  bindPickerChange: function (e) {
    // payment_id 0微信，1货到付款）
    this.setData({
      pay_index: Number(e.detail.value)
    });
    console.log(e.detail.value)
    if (parseInt(e.detail.value)== 0){
      //  说明是微信
      this.setData({
        state:0
      })
    }else{
      this.setData({
        state: 1
      })
    }
  },
  // 填写备注信息
  bindinput: function (e) {
    this.data.remark_data = e.detail.value;
  },
  // 新增订单
  submitOrder: function (e) {
    // 收货地址  （orderData.contact）
    let address = wx.getStorageSync("shippingAddress");
    if (!address.addr) {
      wx.showModal({
        title: "提示",
        content: "请选择收货地址",
        showCancel: false
      });
      return;
    }
    console.log("ssss");
    console.log(this.data.state);
    if(this.data.state==1){
      
      wx.cloud.callFunction({
        // 云函数名称
        name: 'order-add',
        // 传给云函数的参数
        data: {
          diyId:wx.getStorageSync('diyId'),
          sp: this.data.buyData,
          ordernumber: this.genOrderNum(),
          yf: this.data.buyData[0].yf,
          price: this.data.totalPrice,
          address: address.addr,
          name: address.userName,
          phone: address.telNumber,
          remark: this.data.remark_data,
          payment: this.data.pay_index,  //0表示微信支付 
          freeprice:this.data.feePrice,
          couponprice:this.data.couponPrice,
          state: this.data.state, // 0代付款 1 待发货 2 待收货 3退/换货  
          createtime: util.formatTime(new Date())
        },
        complete: res => {
          // this.showSubSuccess();
          console.log('callFunction test result: ', res)
          if (res.errMsg == "cloud.callFunction:ok") {
            this.hideModal();
            this.del();
            this.wxPay(res.result);
          } else {
            wx.showModal({
              title: "提示",
              content: res.errmsg ? res.errmsg : "参数有误",
              showCancel: false
            });
          }

        }
      })
      return;
    }else{
     wx.showToast({
        title: '微信支付正在开通中',
        icon: 'none',
        duration: 2000
      })
      //微信支付运营的
      // wx.cloud.callFunction({
      //   // 云函数名称
      //   name: 'pay',
      //   // 传给云函数的参数
      //   data: {
      //     type: 'unifiedorder',
      //     data: {
      //       goodId: this.data.buyData[0]._id
      //     },
      //     diyId: wx.getStorageSync('diyId'),
      //     sp: this.data.buyData,
      //     ordernumber: this.genOrderNum(),
      //     yf: this.data.buyData[0].yf,
      //     price: this.data.totalPrice,
      //     address: address.addr,
      //     name: address.userName,
      //     phone: address.telNumber,
      //     remark: this.data.remark_data,
      //     payment: this.data.pay_index,  //0表示微信支付 
      //     state: this.data.state, // 0代付款 1 待发货 2 待收货 3退/换货  
      //     createtime: util.formatTime(new Date())
      //   },
      //   complete: res => {
      //     // this.showSubSuccess();
      //     console.log('callFunction test result: ', res)
      //     this.hideModal();
      //     this.del();
      //     let out_trade_no = res.result.data.out_trade_no;
      //     this.setData({
      //       out_trade_no: out_trade_no
      //     })
      //     this.getOrder(res.result.data.order_id);

      //   }
      // })
      return;
    }
  
  },
  /**
   * 获取订单详情
   */
  getOrder: function (order_id) {

  wx.cloud.callFunction({
      name: 'pay',
      data: {
        type: 'orderquery',
        diyId: wx.getStorageSync('diyId'),
        data: {
          out_trade_no: this.data.out_trade_no,
          diyId:wx.getStorageSync('diyId')
        }
    },
    success(res) {
      let data = res.data || {};

      console.log(data);

      this.setData({
        order: data
      });
      let orderQuery = this.data.order;
      let out_trade_no = this.data.out_trade_no;
      let _this = this;

      const {
        time_stamp,
        nonce_str,
        sign,
        sign_type,
        prepay_id,
        body,
        total_fee
      } = orderQuery;

      wx.requestPayment({
        timeStamp: time_stamp,
        nonceStr: nonce_str,
        package: `prepay_id=${prepay_id}`,
        signType: 'MD5',
        paySign: sign,
        async success(res) {
          wx.showLoading({
            title: '正在支付',
          });

          wx.showToast({
            title: '支付成功',
            icon: 'success',
            duration: 1500,
            async success() {
              // _this.getOrder();

              await wx.cloud.callFunction({
                name: 'pay',
                data: {
                  type: 'payorder',
                  diyId:wx.getStorageSync('diyId'),
                  data: {
                    body,
                    prepay_id,
                    out_trade_no,
                    total_fee
                  }
                }
              });
              wx.hideLoading();

              //todo
              // wx.redirectTo({
              //   url: '../order-detail/index?order_id=' + order_id
              // });
            }
          });
        },
        fail: function (res) { }
      })
    },
    fail: console.error
    });

   

    
  },
  // 微信支付
  wxPay(data) {
 


    console.log(data)
    wx.redirectTo({
      url: '../order-detail/index?order_id=' + data._id
    });
  },
  del: function () {
    // 删除已提交的购物车数据
    wx.removeStorageSync('save-now');
    let cartData = wx.getStorageSync('cart-data') ? JSON.parse(wx.getStorageSync('cart-data')) : [];
    if (cartData.length) {
      let i = cartData.length;
      while (i--) {
        if (cartData[i].is_select) {
          cartData.splice(i, 1);
        }
      }
    }
    wx.setStorageSync("cart-data", JSON.stringify(cartData));
  },
  // 发送模板消息
  send_tplmsg: function (formId, order_id) {
    formId = formId.substring(10);
    wx.doodoo.fetch("/api/order/sendPayTpl", {
      method: "GET",
      data: {
        formId: formId,
        orderId: order_id
      }
    }, res => {
      console.log("发送模板消息", res);
    });
  },
  genOrderNum(){
      const date = new Date()
    var year = date.getFullYear()
    var month = (date.getMonth() + 1)>9?date.getMonth()+1:'0'+(date.getMonth()+1);
    var day = date.getDate()>9?date.getDate():('0'+date.getDate())

    var hour = date.getHours()>9?date.getHours():'0'+date.getHours()
    var minute = date.getMinutes()>9?date.getMinutes():'0'+date.getMinutes()
    var second = date.getSeconds()>9?date.getSeconds():'0'+date.getSeconds() 
    var outTradeNo = "";  //订单号
    for (var i = 0; i < 3; i++) //3位随机数，用以加在时间戳后面。
    {
      outTradeNo += Math.floor(Math.random() * 10);
    }
    return year.toString() + month.toString() + day.toString() + hour.toString() + minute.toString() + second.toString() + outTradeNo.toString();
  },
  wxpay(){
    
    let orderQuery = this.data.order;
    let out_trade_no = this.data.out_trade_no;
    let _this = this;

    const {
      time_stamp,
      nonce_str,
      sign,
      sign_type,
      prepay_id,
      body,
      total_fee
    } = orderQuery;

    wx.requestPayment({
      timeStamp: time_stamp,
      nonceStr: nonce_str,
      package: `prepay_id=${prepay_id}`,
      signType: 'MD5',
      paySign: sign,
      async success(res) {
        wx.showLoading({
          title: '正在支付',
        });

        wx.showToast({
          title: '支付成功',
          icon: 'success',
          duration: 1500,
          async success() {
            _this.getOrder();

            await wx.cloud.callFunction({
              name: 'pay',
              data: {
                type: 'payorder',
                diyId: wx.getStorageSync('diyId'),
                data: {
                  body,
                  prepay_id,
                  out_trade_no,
                  total_fee
                }
              }
            });
            wx.hideLoading();
          }
        });
      },
      fail: function (res) { }
    })

  }


});